<template>
  <view class="padding-bottom">
    <view v-if="isDone && (!serviceData || !serviceData.packageName)" class="noData"> 无服务，请换其他服务 </view>
    <view v-if="isDone && serviceData.packageName">
      <view class="uni-padding-wrap">
        <view class="page-section swiper">
          <view class="page-section-spacing">
            <swiper
              class="swiper"
              :autoplay="autoplay"
              :current="currentSwiper"
              :interval="interval"
              :duration="duration"
              :circular="true"
              @change="currentChange"
            >
              <swiper-item v-if="serviceData.videoUrl">
                <view class="swiper-item uni-bg-red">
                  <video
                    id="myVideo"
                    class="myVideo"
                    :src="serviceData.videoUrl"
                    :poster="serviceData.videoImg"
                    controls
                    :enable-progress-gesture="false"
                    @play="playVideo"
                    @pause="pauseVideo"
                    @error="videoErrorCallback"
                  ></video>
                </view>
              </swiper-item>
              <swiper-item v-for="(item, index) in topImg" :key="index">
                <view class="swiper-item uni-bg-green">
                  <view class="topImg"><img class="swiperImg" mode="aspectFit" :src="item.url" /></view>
                </view>
              </swiper-item>
            </swiper>
          </view>
        </view>
      </view>
      <view v-if="topImg.length > 1 || (topImg.length > 0 && serviceData.videoUrl)" class="swiperRadio">
        <span
          v-for="(item, index) in Number(topImg.length + 1)"
          :key="index"
          :class="[currentSwiper === index ? 'cur' : '']"
          @click="currentSwiperFun(index)"
        ></span>
      </view>
      <view class="box">
        <view class="topImg"><img mode="widthFix" :src="topImg.url" /></view>
        <view class="plan">
          <!-- <view class="title">{{serviceData}}</view> -->
          <view class="title">服务套餐详情</view>
          <view class="body">
            <view
              v-for="(item, index) in serviceData.insurancePackagePros[0].insuranceServices"
              :key="index"
              class="row"
              >{{ item.serviceName }}</view
            >
          </view>
        </view>
        <view v-if="serviceData.status === 1" class="css-box">
          <view class="tab-box">
            <view
              v-for="(item, index) in tabs"
              :key="item"
              :class="['tabs', current === index ? 'active-tabs' : '']"
              @click="clickTab(index)"
            >
              {{ item }}
            </view>
          </view>
        </view>
        <view v-if="serviceData.status === 1" class="navBody">
          <view id="target" class="tab-views">
            <img v-for="(item, index) in navOne" :key="index" class="imgWidth" mode="widthFix" :src="item.url" />
          </view>
          <view id="types" class="tab-views">
            <img v-for="(item, index) in navTwo" :key="index" class="imgWidth" mode="widthFix" :src="item.url" />
            <!-- <img class="imgWidth" mode="widthFix" :src="navTwo.url" /> -->
          </view>
          <view id="joinNow" class="tab-views"></view>
        </view>
        <view v-if="serviceData.status === 1 && productItem && productItem.length > 0" class="plan">
          <view class="tip">更多方案详情请阅读以下内容</view>
          <view class="articleList">
            <view v-for="(item, index) in productItem" :key="index" class="liCss" @click="lookArticle(item)">
              <view v-show="(item.name && item.articleId) || (item.name && item.externalLink)">
                {{ item.name }}
              </view>
            </view>
          </view>
        </view>
      </view>
      <fixed-bottom-button v-if="isLogin" :class="[serviceData.status === 1 ? '' : 'bot-btn-disabled']">
        <view v-if="serviceData.status === 1" class="buyCard">
          <view v-if="serviceData.insurancePackagePros[0].salesPrice" class="buyText">
            ¥
            <span class="price">
              {{ (serviceData.insurancePackagePros[0].salesPrice / 100).toFixed(2) }}
            </span>
            /年
            <span
              v-if="
                serviceData.insurancePackagePros[0].marketPrice &&
                serviceData.insurancePackagePros[0].salesPrice !== serviceData.insurancePackagePros[0].marketPrice
              "
              class="priceUnit"
            >
              {{ (serviceData.insurancePackagePros[0].marketPrice / 100).toFixed(2) }}/年
            </span>
          </view>
          <view v-else class="buyText">
            <span class="price"> 免费 </span>
          </view>
          <button
            class="buyBut"
            @click="
              jumpServiceSalePage('/pagesC/service/serviceSale?price=' + serviceData.insurancePackagePros[0].salesPrice)
            "
          >
            {{ serviceData.navThreeDesc }}
          </button>
        </view>
        <view v-if="serviceData.status === 0" class="b-stop"> 已停售 </view>
      </fixed-bottom-button>
      <fixed-bottom-button v-else>
        <view class="toLogin" @click="goLoginPage">
          登录后查看对应的会员优惠价格
          <span class="loginSpan">登录</span>
        </view>
      </fixed-bottom-button>
    </view>
  </view>
</template>

<script>
import testIcon from './../images/warning.png';
import { throttle } from '@/utils/optimize';
import fixedBottomButton from '@/components/fixedBottomBtn';
import { videoDoctor7TrialServiceId } from '@/common/baseUrl';
// import { baseURL } from '@/common/baseUrl.js';
import { getServerPackInof, getCurrentUserInfo } from '@/api/join.js'; // getServicePackLink
import { tongji } from '@/utils/tools';
// import { mapState } from 'vuex';
export default {
  filters: {
    priceFilters: function (val) {
      if (Number(val) === 0) {
        return '免费';
      }
    }
  },
  components: {
    fixedBottomButton
    // cityCom
  },
  data() {
    return {
      patientId: '',
      // serviceId: '',
      test: testIcon,
      current: 0,
      tabs: [],
      timeCount: true,
      // 社区小程序
      isLogin: wx.getStorageSync('token') || false,
      serviceData: {},
      isDone: false,
      topImg: '',
      navOne: '',
      navTwo: '',
      linkData: {},
      productItem: [],
      serviceId: '',
      background: ['color1', 'color2', 'color3'],
      indicatorDots: true,
      autoplay: true,
      interval: 5000,
      duration: 500,
      currentSwiper: 0,
      src: '',
      videoContext: '',
      currentUserInfo: {}
    };
  },

  onLoad: function (option) {
    // console.log('onLoad option:', option);
    if (option && option.id) {
      this.serviceId =
        option.id ||
        (wx.getStorageSync('appSourceQuery') && wx.getStorageSync('appSourceQuery').id) ||
        videoDoctor7TrialServiceId;
      // this.$store.commit('join/SET_COMMUNITYSERVICEID', option.id);
    } else {
      // console.log('this.$store.state.service.launchOptions:', this.$store.state.service.launchOptions);
      this.serviceId =
        this.$store.state.service.launchOptions &&
        this.$store.state.service.launchOptions.query &&
        this.$store.state.service.launchOptions.query.id;
      // this.patientId = 'f6dab639ff554ef39927d22589df7536';
      // this.optionRelation = Number(2) || '';
    }
    tongji('6f0e9aa6-eafa-4df5-9687-d0e74e45e1d8');
    if (wx.getStorageSync('token')) {
      getCurrentUserInfo().then((res) => {
        if (res.code === 0) {
          this.currentUserInfo = res.data;
        } else {
          this.$message({
            type: 'error',
            message: '获取当前用户信息失败'
          });
        }
      });
    }
  },
  onShow() {
    this.isLogin = wx.getStorageSync('token') || false; // 登录返回后数据重新拉取更新
    // 将mounted中的代码移动到onShow
    if (!this.serviceId) {
      this.serviceId = this.$store.state.join.communityServiceId || videoDoctor7TrialServiceId;
    }
    this.getServerPackInoFun();
    this.videoContext = uni.createVideoContext('myVideo');
  },
  computed: {
    // ...mapState('join', {
    //   // serviceId: 'communityServiceId'
    // })
  },
  watch: {
    serviceId: {
      handler: function (newV, oldV) {
        console.log('watch serviceId :', newV, oldV);
        this.serviceId = newV;
        if (this.serviceId) {
          this.getServerPackInoFun();
        }
      },
      immediate: true
    }
  },
  onPageScroll: throttle(function (e) {
    // eslint-disable-next-line
    if (this.timeCount && this.serviceData.status === 1) {
      // eslint-disable-next-line
      this.tabViewHeight();
    }
  }, 60),
  methods: {
    // 需求2671，只需要分享给朋友
    onShareAppMessage: function (e) {
      let pages = getCurrentPages();
      let page = pages[pages.length - 1];
      return {
        title: this.serviceData.shareTitle,
        path: ((page && page.$page.fullPath) || '/pagesC/service/index') + '?cid=' + this.currentUserInfo.cid,
        imageUrl: this.serviceData.shareImg
      };
    },
    async getServerPackInoFun() {
      const { data } = await getServerPackInof(this.serviceId);
      // try {
      //   const { data: artLink } = await getServicePackLink(this.serviceId);
      //   this.linkData = artLink.productSpecs.filter((item) => item.type === 6);
      // } catch {
      //   console.log('外链读取失败');
      // }
      if (!data || data.length < 1) {
        this.isDone = true;
        return false;
      }
      this.serviceData = data[0];
      // this.serviceData.status = 0;
      // console.log('this.serviceData.medicCardType:', typeof this.serviceData.medicCardType);
      // console.log('this.serviceId:', typeof this.serviceId);
      // console.log('this.videoDoctor7TrialServiceId:', typeof videoDoctor7TrialServiceId);
      if (this.serviceData.medicCardType === 2 && videoDoctor7TrialServiceId === Number(this.serviceId)) {
        wx.setStorageSync('hasVisitVideoDoctor7Trial', 1);
      }
      // this.serviceData.insurancePackageSpecs.push(...this.linkData);
      let titleIten = [];
      titleIten.push(data[0].navOneDesc);
      titleIten.push(data[0].navTwoDesc);
      titleIten.push(data[0].navThreeDesc);
      this.tabs = titleIten;
      // 头图
      this.topImg = data[0].insurancePackageSpecs.filter((item) => {
        return item.type === 3;
      });
      // 导航1内容图
      this.navOne = [];
      this.navTwo = [];
      data[0].insurancePackageSpecs.forEach((item) => {
        if (item.type === 4) {
          this.navOne.push(item);
        }
      });
      // 导航2内容图
      data[0].insurancePackageSpecs.forEach((item) => {
        if (item.type === 5) {
          this.navTwo.push(item);
        }
      });
      this.productItem = [];
      let filterData = this.serviceData.insurancePackagePros[0].insuranceServices || [];
      const filterDataTar = this.serviceData.insurancePackageSpecs || [];
      filterData = Array.from(new Set(filterData.map((item) => item.type)));
      filterData.forEach((item) => {
        const getD = filterDataTar.filter(
          (kidItem) =>
            kidItem.productType === item &&
            (kidItem.type === 101 || kidItem.type === 105 || kidItem.type === 106 || kidItem.type === 110)
        );
        this.productItem.push(...getD);
      });
      const getD = filterDataTar.filter(
        (kidItem) =>
          (!kidItem.productType &&
            kidItem.articleId &&
            (kidItem.type === 7 || kidItem.type === 8 || kidItem.type === 9)) ||
          (!kidItem.productType &&
            kidItem.externalLink &&
            (kidItem.type === 7 || kidItem.type === 8 || kidItem.type === 9))
      );
      this.productItem.push(...getD);
      uni.setNavigationBarTitle({
        title: this.serviceData.packageName || '服务领取'
      });
      this.isDone = true;
    },
    // 点击tab
    clickTab(i) {
      // [健康资产分析, 大病风险, 指导建议] id选择器
      const self = this;
      this.timeCount = false;
      setTimeout(function () {
        self.timeCount = true;
      }, 1000);
      const view_class = ['#target', '#types', '#joinNow'];
      const query = uni.createSelectorQuery();
      this.current = i;
      query.select(view_class[i]).boundingClientRect();
      query.selectViewport().scrollOffset();
      query.exec((res) => {
        uni.pageScrollTo({
          scrollTop: res[0].top + res[1].scrollTop - 58,
          duration: 60
        });
      });
    },

    // 计算tabView高度
    tabViewHeight() {
      const query = uni.createSelectorQuery();
      query
        .selectAll('.tab-views')
        .boundingClientRect()
        .exec((res) => {
          if (res) {
            const rect = res[0];
            for (let i = 2; i >= 0; i--) {
              if (rect[i].top <= 58) {
                this.current = i;
                return;
              } else {
                this.current = 0;
              }
            }
          }
        });
    },
    goLoginPage(url) {
      // eslint-disable-next-line
      const routes = getCurrentPages();
      const routesSrc = routes[routes.length - 1].route;
      const curRoute = url && typeof url === 'string' ? url : routesSrc; // 获取当前页面路由

      this.$store.commit('join/SET_REFERERS', curRoute.startsWith('/pages') ? `${curRoute}` : `/${curRoute}`);
      this.$wxPromise.navigateTo({
        url: '/pages/join/index'
      });
    },
    lookArticle(data) {
      if (data.articleId && data.name) {
        this.link(data.articleId);
        return false;
      }
      // 外链
      const links = data.externalLink;
      let externalLinkDomain = links.split('/')[2].split('.').join('');
      uni.navigateTo({
        url: `pages/view/outer-view?externalLinkDomain=${externalLinkDomain}&url=${links}`
      });
    },
    jumpServiceSalePage(urls) {
      this.$store.commit('join/SET_COMMUNITYSERVICEID', this.serviceId);
      this.$wxPromise.navigateTo({
        url: urls
      });
      tongji('b577b1df-7544-4250-86b7-d284aca27dc6');
    },
    link(id) {
      this.$wxPromise.navigateTo({
        url: '/pages/agreementReading/index?articleId=' + id
      });
    },
    changeIndicatorDots(e) {
      this.indicatorDots = !this.indicatorDots;
    },
    changeAutoplay(e) {
      this.autoplay = !this.autoplay;
    },
    intervalChange(e) {
      this.interval = e.target.value;
    },
    durationChange(e) {
      this.duration = e.target.value;
    },
    videoErrorCallback: function (e) {
      uni.showModal({
        content: e.target.errMsg,
        showCancel: false
      });
    },
    currentChange(e) {
      const index = e.detail.current;
      this.currentSwiper = index;
      if (index !== 0) {
        this.videoContext.pause();
      }
    },
    playVideo() {
      this.autoplay = false;
    },
    pauseVideo() {
      this.autoplay = true;
    },
    currentSwiperFun(index) {
      const self = this;
      this.autoplay = false;
      this.currentSwiper = index;
      setTimeout(function () {
        self.autoplay = true;
      }, self.interval);
    }
  }
};
</script>

<style lang="scss">
@import './../style/common.scss';
.box {
  padding-bottom: 180rpx;
  .topImg {
    text-align: center;
    img {
      width: 100%;
      height: auto;
      display: block;
    }
  }
  .plan {
    padding: 24rpx;
    padding-top: 0;
    margin-bottom: 24rpx;
    background-color: #fff;
    .title {
      font-size: 36rpx;
      padding: 24rpx 0;
      font-weight: bold;
    }
    .body {
      background-color: #f4f4f4;
      padding: 4rpx 14rpx;
      font-size: 28rpx;
      color: rgba(0, 0, 0, 0.7);
      border-radius: 16rpx;
      .row {
        margin: 14rpx;
        font-size: 32rpx;
      }
    }
    .tip {
      font-size: 28rpx;
      color: rgba(178, 178, 178, 1);
      padding: 30rpx 0 12rpx 0;
    }
    .articleList {
      .liCss {
        color: #2680eb;
        font-size: 28rpx;
        margin: 12rpx 0;
      }
    }
  }
}
.css-box {
  // border-radius: 16rpx;
  background: #ffffff;
  font-weight: 400;
  // position: relative;
  border-bottom-left-radius: 0;
  border-bottom-right-radius: 0;
  position: sticky;
  position: -webkit-sticky;
  top: 0px;
  left: 0;
  z-index: 9;
}
// .css-box::after {
//   content: ' ';
//   display: block;
//   position: absolute;
//   top: 90rpx;
//   z-index: -1;
//   width: 100%;
//   height: 80rpx;
//   background-image: linear-gradient(0deg, rgba(255, 255, 255, 0) 0%, white 70%);
// }
.tab-box {
  display: flex;
  align-items: center;
  font-size: 32rpx;
  justify-content: space-between;
  margin: 0 48rpx;
  border-bottom: 1px solid #e8e8e8;
  // margin: 24rpx;
  // border-radius: 16rpx;
  // background-color: #fff;
  // position: sticky;
  // position: -webkit-sticky;
  // top: 0px;
  // left: 0;
  // z-index: 9;
  // box-shadow: 0 4px 10px 0px #ffffff;
  // margin-bottom: 0;
  .tabs {
    padding: 24rpx 0 16rpx;
    position: relative;
    top: 0;
    width: 200rpx;
    text-align: center;
  }
  .active-tabs {
    color: #f34e1c;
    font-weight: 500;
  }
  .active-tabs::after {
    content: ' ';
    width: 100%;
    height: 1px;
    background: #f34e1c;
    position: absolute;
    bottom: -1px;
    left: 0;
    margin: auto;
    right: 0;
  }
}
.buyCard {
  color: #f34e1c;
  position: relative;
  width: 100%;
  // padding-bottom:10rpx;
  .buyText {
    padding-right: 260rpx;
    margin-top: 12rpx;
    font-size: 28rpx;
    white-space: nowrap;
    .tip {
      display: inline-block;
      margin-right: 14rpx;
      background-color: #fee9e9;
      border-radius: 4rpx;
      padding: 0 8rpx;
    }
    .price {
      font-size: 44rpx;
    }
    .priceUnit {
      color: #b2b2b2;
      padding: 0 16rpx;
      text-decoration: line-through;
    }
  }
  .buyBut {
    position: absolute;
    display: inline-block;
    width: 240rpx;
    height: 88rpx;
    border-radius: 44rpx;
    right: 0;
    top: 0;
    color: #fff;
    background: linear-gradient(236deg, #fe894d 0%, #ef3931 100%);
  }
}
.toLogin {
  font-size: 32rpx;
  text-align: center;
  .loginSpan {
    display: inline-block;
    background: #f34e1c;
    color: #fff;
    margin-left: 20rpx;
    padding: 10rpx 46rpx;
    border-radius: 48rpx;
    text-align: center;
  }
}
.imgWidth {
  width: 100%;
  display: block;
}
.noData {
  font-size: 28rpx;
  text-align: center;
  padding: 40rpx;
  color: #999;
}
.navBody {
  padding-top: 2rpx;
}
.swiper,
.myVideo {
  width: 750rpx;
  height: 750rpx;
}
.topImg {
  text-align: center;
  img {
    display: block;
    height: 750rpx;
    width: auto;
  }
  .swiperImg {
    height: 750rpx !important;
    width: auto;
    max-width: 750rpx;
  }
}
.swiperRadio {
  margin: 30rpx;
  text-align: center;
  span {
    display: inline-block;
    width: 20rpx;
    height: 20rpx;
    background-color: #000;
    margin: 10rpx;
    border-radius: 20rpx;
  }
  .cur {
    background-color: #f34e1c;
  }
}
.bot-btn-disabled {
  .fix-bottom-btn {
    background: rgba(0, 0, 0, 0.7) !important;
  }
  .b-stop {
    color: white;
  }
}
</style>
